/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RegistroDactilarFrame.java
 *
 * Created on 21-sep-2010, 17:36:42
 */

package INTERFAZ;

import CONTROLES.ControlCliente;
import CONTROLES.HabilitarHuella;
import CONTROLES.HabilitarLector;
import CONTROLES.SeleccionDactilar;
import MODELOS.Cliente;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;

/**
 *
 * @author Administrador
 */
public class RegistroDactilarFrame extends javax.swing.JFrame {

    private Cliente idClienteARegistrar;
    private String ruta;
    private ArrayList<SeleccionDactilar> seleccion=new ArrayList<SeleccionDactilar>();

    private BufferedImage imagenHuella = null;

    private JPanel nuevoPanel;

     private ByteArrayInputStream huellasDatos;

   /**Arreglo que contiene la longitud del dato de la huella*/
   private int huellaLongitud;

    private HabilitarHuella lector;
    



    public Cliente getIdClienteARegistrar() {
        return idClienteARegistrar;
    }

    public void setIdClienteARegistrar(Cliente idClienteARegistrar) {
        this.idClienteARegistrar = idClienteARegistrar;
    }

    public String getRuta()
    {
        return ruta;
    }

    public void setRuta(String ruta)
    {
        this.ruta = ruta;
    }


    /** Creates new form RegistroDactilarFrame */
    public RegistroDactilarFrame() {
         inicializar();
        initComponents();
        setResizable(false);
        lector.inicializarCaptura();
    }


    public void huellaLeida(){
        btn_siguiente.setEnabled(true);
        


    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelHuella = new javax.swing.JPanel();
        btn_siguiente = new javax.swing.JButton();
        lbl_info = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Captura de Huellas");
        setAlwaysOnTop(true);
        setBackground(new java.awt.Color(51, 153, 255));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        panelHuella.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Huella Capturada", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 0, 0))); // NOI18N
        panelHuella.setLayout(new java.awt.BorderLayout());

        btn_siguiente.setEnabled(false);
        btn_siguiente.setLabel("SIGUIENTE");
        btn_siguiente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_siguienteActionPerformed(evt);
            }
        });

        lbl_info.setBackground(java.awt.Color.white);
        lbl_info.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lbl_info.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lbl_info.setText("jLabel3");
        lbl_info.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Instrucción", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("DejaVu Sans", 0, 11))); // NOI18N
        lbl_info.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(225, 225, 225)
                .addComponent(btn_siguiente, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(189, Short.MAX_VALUE))
            .addComponent(lbl_info, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(105, 105, 105)
                .addComponent(panelHuella, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(109, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(panelHuella, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lbl_info, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btn_siguiente)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        panelHuella.add(crearPanel());
    }//GEN-LAST:event_formWindowActivated

    private void btn_siguienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_siguienteActionPerformed
        // TODO add your handling code here:
        registrarHuella();
        comenzarIteracion();

        showImage(null);
    }//GEN-LAST:event_btn_siguienteActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        JOptionPane.showMessageDialog(this, "Todavia Faltan huellas por registrar.", "Advertencia", JOptionPane.OK_OPTION);
    }//GEN-LAST:event_formWindowClosing

    public void actualizar(SeleccionDactilar s){
        lbl_info.setText(s.getMensaje());
        //ImageIcon im=new ImageIcon(s.getImagenReferencia().getImage().getScaledInstance(250, 280, 1));
        //lbl_referencia.setIcon(im);
        btn_siguiente.setEnabled(false);
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RegistroDactilarFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_siguiente;
    private javax.swing.JLabel lbl_info;
    private javax.swing.JPanel panelHuella;
    // End of variables declaration//GEN-END:variables

    private void registrarHuella() {
        SeleccionDactilar selec=seleccion.get(i);
        
        System.out.println("registrandooooooooooooooooooooooooo en BD.. mano= "+selec.getMANO()+" .. dedo= "+selec.getDEDO()+"... id="+getIdClienteARegistrar());
        i++;
        ControlCliente co = new ControlCliente();
        String mano = selec.getMANO();
        String dedo = selec.getDEDO();

        
        if(i<=1)
        {
            co.guardarCliente(getIdClienteARegistrar(),getRuta());
        }
         
        Cliente cli2 = co.dameClienteCi(getIdClienteARegistrar().getCiCliente());
        int idEmp= cli2.getIdCliente();
        lector.guardarHuella( mano, dedo, idEmp);
        
       

        System.out.println("salio de guardar huella ========== ");


    }

    void setSeleccion(ArrayList<SeleccionDactilar> seleccion) {
        this.seleccion=seleccion;
        comenzarIteracion();
    }

    int i=0;
    private void comenzarIteracion() {
        if(i<seleccion.size()){
            actualizar(seleccion.get(i));
            
        }else{

             JOptionPane j=new JOptionPane();
            j.showMessageDialog(this, "El CLIENTE y sus Huellas dactilares se registraron correctamente", "Información", JOptionPane.PLAIN_MESSAGE);
            lector.terminarCaptura();
            dispose();
            parent.dispose();
        }
    }

    public void inicializar() {

       try {
           UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
       } catch (Exception e) {
            System.err.println("No se pudo aplicar el estilo visual");
       }

       //Crea una instancia de Util
       lector = new HabilitarHuella(this);
   }

    public JComponent crearPanel() {
       //Crea un panel nuevo para mostrar la huella
       nuevoPanel = new JPanel(){

           //Se sobreescribe el método paintComponent para habilitar la muestra de la imagen de la huella
           public void paintComponent(Graphics g) {
               super.paintComponent(g);
               
               //Si hay una imagen para ser mostrada
               if (imagenHuella!=null) {
                   //Calcula el tamaño y posición de la imagen para ser pintada
                   //el tamaño es ajustado para que ocupe todo el tamaño del panel
                   Insets insets = getInsets();
                   int transX = insets.left;
                   int transY = insets.top;
                   int width  = getWidth()  - getInsets().right  - getInsets().left;
                   int height = getHeight() - getInsets().bottom - getInsets().top;

                   //Se dibuja la imagen
                   g.drawImage(imagenHuella, transX, transY, width, height, null);
                   huellaLeida();
               }

           }

       };

       //Se agrega un border alrededor del panel
       nuevoPanel.setBorder(new CompoundBorder (
               new EmptyBorder (2,2,2,2),
               new BevelBorder(BevelBorder.LOWERED)));

       nuevoPanel.setToolTipText("Imagen de la última huella capturada.");

       if(nuevoPanel==null)
       {
            System.exit(1);
            return null;
       }else{

       return nuevoPanel;
       }

   }

     public void showImage(BufferedImage imagen)
    {
        System.out.println("imagen........................ ");



        imagenHuella = imagen;
        repaint();

    }

     RegistroDactilar1 parent;
    void setParent(RegistroDactilar1 aThis) {
        parent=aThis;

    }


}
